#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <pfring.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define DEVICE "eth0" // 需要使用 PF_RING 的网络接口

// 计算 IP 头部长度
#define IP_HEADER_LEN(ip_header) ((ip_header->ip_hl & 0x0f) * 4)

// 计算 TCP 头部长度
#define TCP_HEADER_LEN(tcp_header) ((tcp_header->doff & 0x0f) * 4)

void process_packet(const u_char* packet, int len, pfring* ring)
{
    // 解析 IP 头部
    struct iphdr* ip_header = (struct iphdr*)(packet + 14);
    struct tcphdr* tcp_header = (struct tcphdr*)(packet + 14 + IP_HEADER_LEN(ip_header));

    // 简单的检查以确认是 TCP 数据包
    if (ip_header->protocol == IPPROTO_TCP) {
        int ip_header_len = IP_HEADER_LEN(ip_header);
        int tcp_header_len = TCP_HEADER_LEN(tcp_header);
        const u_char* data = packet + 14 + ip_header_len + tcp_header_len;
        int data_len = len - (14 + ip_header_len + tcp_header_len);

        // 构建响应数据包
        u_char* response = malloc(len);
        memcpy(response, packet, len);

        // 发送数据包
        pfring_send(ring, response, len);
        free(response);
    }
}

int main()
{
    pfring* ring;
    char errbuf[PCAP_ERRBUF_SIZE];

    // 初始化 PF_RING
    ring = pfring_open(DEVICE, 1500, PF_RING_PROMISC);
    if (!ring) {
        fprintf(stderr, "Failed to open PF_RING interface\n");
        return 1;
    }

    if (pfring_set_direction(ring, PF_RING_RECV_ONLY) != 0) {
        fprintf(stderr, "Failed to set PF_RING direction\n");
        pfring_close(ring);
        return 1;
    }

    if (pfring_enable_ring(ring) != 0) {
        fprintf(stderr, "Failed to enable PF_RING\n");
        pfring_close(ring);
        return 1;
    }

    // 捕获和处理数据包
    while (1) {
        pfring_pkthdr hdr;
        u_char* pkt;
        int res = pfring_recv(ring, &pkt, &hdr, 1);

        if (res > 0) {
            process_packet(pkt, hdr.len, ring);
        }

        if (res < 0) {
            fprintf(stderr, "Error receiving packet\n");
        }
    }

    pfring_close(ring);
    return 0;
}
